package com.iss.ljx.role.service.impl;

import com.iss.ljx.mybatis.entity.PtRoleEntity;
import com.iss.ljx.mybatis.flexigrid.PadingRstType;
import com.iss.ljx.mybatis.flexigrid.PagingBean;
import com.iss.ljx.mybatis.ztree.ZtreeEntity;
import com.iss.ljx.role.entity.SearchRoleEntity;
import com.iss.ljx.role.repository.RoleDao;
import com.iss.ljx.role.service.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;

    @Override
    public PadingRstType<PtRoleEntity> queryRoleListPage(SearchRoleEntity search, PagingBean paging) {
        paging.deal(PtRoleEntity.class);
        PadingRstType<PtRoleEntity> ptRoleEntityPadingRstType = new PadingRstType<PtRoleEntity>();
        ptRoleEntityPadingRstType.setPage(paging.getPage());
        List<PtRoleEntity> list = roleDao.queryRoleListPage(search, paging);
        ptRoleEntityPadingRstType.setRawRecords(list);
        Integer total = roleDao.queryRoleTotal(search);
        ptRoleEntityPadingRstType.setTotal(total);
        ptRoleEntityPadingRstType.putItems();
        return ptRoleEntityPadingRstType;
    }

    @Override
    public List<ZtreeEntity> queryMenuByRoleId(String roleUuid) {

        List<ZtreeEntity> list = roleDao.queryMenuTree();
        List<String> menuIdList = roleDao.queryMenuIdByRoleId(roleUuid);
        int index = 0;
        for (ZtreeEntity item : list) {
            if (index > 10) {
                item.setOpen(false);
            }
            index++;
            for (String menuId : menuIdList) {
                if (menuId.equals(item.getId())) {
                    item.setChecked(true);
                }
            }
        }
        return list;
    }
    @Override
    public void saveMenuIdAndRoleId(String roleUuid, String menuArray) {
        roleDao.deleteMenuByRoleId(roleUuid);
        String[] menuIds = menuArray.split(",");
        for(String menuId: menuIds){
            roleDao.insertMenuAndRole(roleUuid,menuId);
        }
    }

    @Override
    public void roleAdd(PtRoleEntity ptRoleEntity) {
        String uuid= UUID.randomUUID().toString();
        ptRoleEntity.setRoleUuid(uuid);
        roleDao.roleAdd(ptRoleEntity);
    }

    @Override
    public void roleUpdate(PtRoleEntity ptRoleEntity) {
        roleDao.roleUpdate(ptRoleEntity);
    }

    @Override
    public void roleDelete(PtRoleEntity ptRoleEntity) {
        roleDao.roleDelete(ptRoleEntity);
    }

    @Override
    public void saveUserIdAndRoleId(String userUuid, String roleArray) {
        roleDao.deleteUserByRoleId(userUuid);
        String[] roleUuids = roleArray.split(",");
        for(String roleUuid: roleUuids){
            roleDao.insertUserAndRole(userUuid,roleUuid);
        }
    }
}
